#!/usr/bin/env python
#encoding:utf-8
#Create：     2013-7-22
#Author：     longlimin

import os
import traceback
import parser
import utils
import config
import ins


class FileLocker(object):
    
    if os.name =='posix':
        try:
            import fcntl
        except:
            pass
    
    def __init__(self, lockpath):
        self.__file = open(lockpath,'wr')
    
    """ True: 已锁     若文件被锁会抛出异常 """
    def lock(self):
        self.__relocked = False  
        try:
            fcntl.lockf(self.__file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except:
            self.__relocked = True
            return True
        return False
    
    def unlock(self):  
        if not self.__relocked:
            fcntl.flock(self.__file.fileno(), fcntl.LOCK_UN)
            self.__file.close()
            self.__relocked = True  

def run():
    codes = utils.data_points()
    for code in codes:
        try:
            filelock_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "filelock")
            if  os.path.exists(filelock_path):
                os.mkdir(filelock_path)
            flock = FileLocker(os.path.join(filelock_path, code))
            if not flock.lock():
                try:
                    lparser = parser.LogParser(code, source_path=config.SOURCE, des_path=config.DES)
                    lparser.start()
                except:
                    ins.errlog(traceback.format_exc())
                flock.unlock()
            else:
                print "sorry another process is running"
        except:
            ins.errlog(traceback.format_exc())

if __name__ == "__main__":
    run()
        
    